<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
</head>
<body>
    <!-- 增强版全局通知组件 -->
    <div th:fragment="notification">
        <!-- 通知弹窗 -->
        <div id="globalNotificationContainer" class="position-fixed" style="top: 20px; right: 20px; z-index: 9999; display: none; max-width: 400px;">
            <div class="alert alert-info alert-dismissible fade show shadow-lg" role="alert" style="border-left: 4px solid #17a2b8;">
                <div class="d-flex align-items-start">
                    <i id="notificationIcon" class="fas fa-bell me-2 mt-1" style="color: #17a2b8;"></i>
                    <div class="flex-grow-1">
                        <h6 id="globalNotificationTitle" class="alert-heading mb-1">新消息</h6>
                        <p id="globalNotificationContent" class="mb-2 small">您有新的消息</p>
                        <div class="d-flex gap-2">
                            <button id="viewMessageBtn" class="btn btn-sm btn-outline-info">查看消息</button>
                            <button id="dismissNotificationBtn" class="btn btn-sm btn-outline-secondary">稍后查看</button>
                        </div>
                    </div>
                </div>
                <button type="button" class="btn-close" onclick="hideGlobalNotification()"></button>
            </div>
        </div>

        <!-- 小红点通知指示器 -->
        <div id="notificationIndicator" class="position-fixed" style="top: 15px; right: 15px; z-index: 10000; display: none;">
            <span class="badge bg-danger rounded-pill" style="font-size: 10px; padding: 4px 6px; cursor: pointer;">
                <span id="indicatorCount">0</span>
            </span>
        </div>

        <!-- 增强版通知脚本 -->
        <script>
            // 全局通知状态
            let globalNotificationState = {
                isActive: false,
                interval: null,
                lastCheckTime: new Date(),
                unreadCount: 0,
                notifications: [],
                currentUserRole: null,
                currentPage: window.location.pathname,
                isVisible: true,
                notificationShown: false,
                lastShownNotificationId: null,
                shownNotificationIds: new Set(),
                currentNotification: null // 当前显示的通知
            };

            // 页面可见性检测
            document.addEventListener('visibilitychange', function() {
                globalNotificationState.isVisible = !document.hidden;
                if (globalNotificationState.isVisible && globalNotificationState.isActive) {
                    checkForNotifications();
                }
            });

            // 页面加载完成后初始化
            document.addEventListener('DOMContentLoaded', function() {
                setTimeout(initializeGlobalNotification, 500);
            });

            // 如果DOM已经加载完成，立即初始化
            if (document.readyState === 'complete' || document.readyState === 'interactive') {
                setTimeout(initializeGlobalNotification, 100);
            }

            // 页面卸载时清理
            window.addEventListener('beforeunload', function() {
                stopGlobalNotification();
            });

            function initializeGlobalNotification() {
                console.log('初始化增强版全局通知系统');
                
                detectUserRole();
                detectPageType();
                
                if (shouldEnableNotification()) {
                    startGlobalNotification();
                } else {
                    console.log('当前页面/角色不需要启用通知:', globalNotificationState.currentPage);
                }

                bindNotificationEvents();
            }

            function detectUserRole() {
                const roleElement = document.querySelector('[data-user-role]');
                if (roleElement) {
                    globalNotificationState.currentUserRole = roleElement.getAttribute('data-user-role');
                    return;
                }

                const path = globalNotificationState.currentPage;
                if (path.includes('/customer-service/')) {
                    globalNotificationState.currentUserRole = 'customer_service';
                } else if (path.includes('/admin/')) {
                    globalNotificationState.currentUserRole = 'admin';
                } else if (path.includes('/customer/') || path === '/' || path === '/home') {
                    globalNotificationState.currentUserRole = 'customer';
                } else {
                    globalNotificationState.currentUserRole = 'unknown';
                }

                console.log('检测到用户角色:', globalNotificationState.currentUserRole);
            }

            function detectPageType() {
                const path = globalNotificationState.currentPage;
                
                if (path.includes('/customer/customer-service') || path.includes('/customer-service/chat/')) {
                    globalNotificationState.isInChatPage = true;
                } else {
                    globalNotificationState.isInChatPage = false;
                }

                console.log('当前页面类型 - 聊天页面:', globalNotificationState.isInChatPage);
            }

            function shouldEnableNotification() {
                const role = globalNotificationState.currentUserRole;
                const isInChatPage = globalNotificationState.isInChatPage;

                if (isInChatPage) {
                    return false;
                }

                return role === 'customer' || role === 'customer_service';
            }

            function startGlobalNotification() {
                if (globalNotificationState.isActive) {
                    return;
                }

                console.log('启动全局通知检查');
                globalNotificationState.isActive = true;

                checkForNotifications();
                globalNotificationState.interval = setInterval(checkForNotifications, 3000);
            }

            function stopGlobalNotification() {
                if (globalNotificationState.interval) {
                    clearInterval(globalNotificationState.interval);
                    globalNotificationState.interval = null;
                }
                globalNotificationState.isActive = false;
                console.log('停止全局通知检查');
            }

            function checkForNotifications() {
                if (!globalNotificationState.isActive || !globalNotificationState.isVisible) {
                    return;
                }

                const role = globalNotificationState.currentUserRole;
                let apiUrl = '';

                if (role === 'customer') {
                    apiUrl = '/customer/notifications';
                } else if (role === 'customer_service') {
                    apiUrl = '/customer-service/notifications';
                } else {
                    return;
                }

                const timestamp = new Date().getTime();
                const urlWithTimestamp = `${apiUrl}?t=${timestamp}`;

                fetch(urlWithTimestamp, {
                    method: 'GET',
                    headers: {
                        'Cache-Control': 'no-cache',
                        'Pragma': 'no-cache'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        handleNotificationResponse(data);
                    } else {
                        console.error('获取通知失败:', data.message);
                    }
                })
                .catch(error => {
                    console.error('通知检查请求失败:', error);
                });
            }

            function handleNotificationResponse(data) {
                const currentUnreadCount = data.unreadCount || 0;
                const notifications = data.notifications || [];
                const previousCount = globalNotificationState.unreadCount;

                console.log('处理通知响应:', {
                    currentUnreadCount,
                    previousCount,
                    notificationsLength: notifications.length,
                    isInChatPage: globalNotificationState.isInChatPage
                });

                // 始终更新小红点
                updateNotificationIndicator(currentUnreadCount);

                // 检查是否需要显示弹窗
                if (currentUnreadCount > 0 && !globalNotificationState.isInChatPage && notifications.length > 0) {
                    const latestNotification = notifications[0];
                    const notificationId = generateNotificationId(latestNotification);
                    
                    // 只有在以下情况才显示弹窗：
                    // 1. 未读数量增加了（有新消息）
                    // 2. 或者是全新的通知ID
                    const shouldShowPopup = (currentUnreadCount > previousCount) || 
                                          (!globalNotificationState.shownNotificationIds.has(notificationId));
                    
                    if (shouldShowPopup && !globalNotificationState.notificationShown) {
                        console.log('显示新通知弹窗:', latestNotification);
                        showGlobalNotification(latestNotification);
                        globalNotificationState.shownNotificationIds.add(notificationId);
                        globalNotificationState.currentNotification = latestNotification;
                    }
                }

                // 更新状态
                globalNotificationState.unreadCount = currentUnreadCount;
                globalNotificationState.notifications = notifications;

                // 如果没有未读消息，清理状态
                if (currentUnreadCount === 0) {
                    hideGlobalNotification();
                    hideNotificationIndicator();
                    globalNotificationState.shownNotificationIds.clear();
                    globalNotificationState.currentNotification = null;
                }
            }

            function generateNotificationId(notification) {
                return `${notification.id || notification.relatedId || 'unknown'}_${notification.createdTime || Date.now()}`;
            }

            function updateNotificationIndicator(count) {
                const indicator = document.getElementById('notificationIndicator');
                const countElement = document.getElementById('indicatorCount');
                
                if (count > 0) {
                    countElement.textContent = count > 99 ? '99+' : count;
                    indicator.style.display = 'block';
                } else {
                    indicator.style.display = 'none';
                }
            }

            function showGlobalNotification(notification) {
                const container = document.getElementById('globalNotificationContainer');
                const title = document.getElementById('globalNotificationTitle');
                const content = document.getElementById('globalNotificationContent');
                const icon = document.getElementById('notificationIcon');

                if (!container || !title || !content) {
                    console.error('通知容器元素未找到');
                    return;
                }

                console.log('显示通知弹窗:', notification);

                const senderName = notification.senderName || '系统';
                const messageContent = notification.messageContent || '您有新的消息，请及时查看';
                
                title.textContent = `${senderName} 发送了消息`;
                content.textContent = messageContent;

                if (notification.notificationType === 'conversation_started') {
                    icon.className = 'fas fa-user-plus me-2 mt-1';
                    title.textContent = `${senderName} 发起了咨询`;
                } else {
                    icon.className = 'fas fa-comment me-2 mt-1';
                }

                // 确保先隐藏
                hideGlobalNotification();
                
                // 显示新通知
                setTimeout(() => {
                    container.style.display = 'block';
                    container.classList.add('animate__animated', 'animate__slideInRight');
                    globalNotificationState.notificationShown = true;
                    
                    console.log('通知弹窗已显示');
                }, 200);

                playNotificationSound();

                // 15秒后自动隐藏
                setTimeout(() => {
                    if (globalNotificationState.notificationShown) {
                        hideGlobalNotification();
                    }
                }, 15000);
            }

            function hideGlobalNotification() {
                const container = document.getElementById('globalNotificationContainer');
                if (container) {
                    container.style.display = 'none';
                    container.classList.remove('animate__animated', 'animate__slideInRight');
                    globalNotificationState.notificationShown = false;
                }
            }

            function hideNotificationIndicator() {
                const indicator = document.getElementById('notificationIndicator');
                if (indicator) {
                    indicator.style.display = 'none';
                }
            }

            function navigateToChat() {
                const role = globalNotificationState.currentUserRole;
                const currentNotification = globalNotificationState.currentNotification;
                
                // 标记所有通知为已读
                markAllNotificationsAsRead();
                
                // 立即隐藏通知
                hideGlobalNotification();
                hideNotificationIndicator();
                
                // 根据角色和通知类型跳转到具体对话
                if (role === 'customer') {
                    // 用户直接跳转到客服聊天页面
                    window.location.href = '/customer/customer-service';
                } else if (role === 'customer_service') {
                    // 客服跳转到具体对话页面
                    if (currentNotification && currentNotification.relatedId) {
                        window.location.href = `/customer-service/chat/${currentNotification.relatedId}`;
                    } else {
                        window.location.href = '/customer-service/conversations';
                    }
                }
            }

            function bindNotificationEvents() {
                // 查看消息按钮 - 直接跳转到对话页面
                const viewBtn = document.getElementById('viewMessageBtn');
                if (viewBtn) {
                    viewBtn.addEventListener('click', navigateToChat);
                }

                // 稍后查看按钮
                const dismissBtn = document.getElementById('dismissNotificationBtn');
                if (dismissBtn) {
                    dismissBtn.addEventListener('click', function() {
                        hideGlobalNotification();
                    });
                }

                // 小红点点击事件 - 直接跳转到对话页面
                const indicator = document.getElementById('notificationIndicator');
                if (indicator) {
                    indicator.addEventListener('click', navigateToChat);
                }
            }

            function markAllNotificationsAsRead() {
                const role = globalNotificationState.currentUserRole;
                let apiUrl = '';

                if (role === 'customer') {
                    apiUrl = '/customer/mark-all-read';
                } else if (role === 'customer_service') {
                    apiUrl = '/customer-service/mark-all-read';
                } else {
                    return;
                }

                fetch(apiUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        console.log('所有通知已标记为已读');
                        globalNotificationState.unreadCount = 0;
                        globalNotificationState.notifications = [];
                        globalNotificationState.notificationShown = false;
                    } else {
                        console.error('标记已读失败:', data.message);
                    }
                })
                .catch(error => {
                    console.error('标记已读请求失败:', error);
                });
            }

            function playNotificationSound() {
                try {
                    const audioContext = new (window.AudioContext || window.webkitAudioContext)();
                    const oscillator = audioContext.createOscillator();
                    const gainNode = audioContext.createGain();
                    
                    oscillator.connect(gainNode);
                    gainNode.connect(audioContext.destination);
                    
                    oscillator.frequency.setValueAtTime(800, audioContext.currentTime);
                    oscillator.frequency.setValueAtTime(600, audioContext.currentTime + 0.1);
                    
                    gainNode.gain.setValueAtTime(0.1, audioContext.currentTime);
                    gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.3);
                    
                    oscillator.start(audioContext.currentTime);
                    oscillator.stop(audioContext.currentTime + 0.3);
                } catch (error) {
                    console.log('无法播放通知音效:', error);
                }
            }

            // 暴露全局接口
            window.globalNotificationSystem = {
                start: startGlobalNotification,
                stop: stopGlobalNotification,
                check: checkForNotifications,
                show: showGlobalNotification,
                hide: hideGlobalNotification,
                markAllRead: markAllNotificationsAsRead,
                navigateToChat: navigateToChat,
                getState: () => globalNotificationState
            };
        </script>
        
        <!-- 添加动画效果 -->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">
    </div>
</html> 